package com.chixing.ih.util;

import com.chixing.ih.config.JwtConfig;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘岩
 * Date: 2020-09-23
 * Time: 22:01
 *
 * @version 1.0
 */
@Component
public class JwtUtil {
    @Autowired
    JwtConfig jwtConfig;

    //创建一个jwt
    public String createJWT(String  userId) {
        JwtBuilder jwtBuilder = Jwts.builder().setId(userId)
                .setIssuedAt(new Date(System.currentTimeMillis()))
                .setExpiration(new Date(System.currentTimeMillis()+JwtConfig.ERROR_TIME))
                .signWith(SignatureAlgorithm.HS256, JwtConfig.TOKEN_SECRET);
        String token = jwtBuilder.compact();
        return token;
    }

    public String createJWT(Claims claims) {
        return createJWT(getId(claims));
    }

    //解析jwt令牌用的
    public Claims parseToken(String token) {
        Claims claims = Jwts.parser()
                .setSigningKey(JwtConfig.TOKEN_SECRET)
                .parseClaimsJws(token)
                .getBody();
        return claims;
    }
    //检查jwt是不是需要更换了
    public boolean isNeedReToken(Claims claims) {
        if (claims.getIssuedAt().getTime() + JwtConfig.WANING_TIME <= System.currentTimeMillis()) {
            return true;
        }
        return false;
    }

    //获取jwt中的id
    public String getId(Claims claims){
        return claims.getId();
    }
}
